package account

import (
	"fmt"
	"github.com/gin-gonic/gin"

	"com.jiaguyu/model"

	"com.jiaguyu/until"

	"com.jiaguyu/dao/db"
	"com.jiaguyu/id_gen"
	"com.jiaguyu/middleware/account"
)

//登陆功能
func LoginHandle(ctx *gin.Context) {
	//
	account.ProcessRequest(ctx)
	var err error
	var userInfo model.UserInfo

	//直接将前端给数据 赋值到结构体
	defer func() {
		if err != nil {
			return
		}
		account.SetUserId(userInfo.UserId, ctx)
		//当调用responseSuccess的时候，gin框架已经把数据发送给浏览器了
		//	所以在responseSuccess之后，SetCookie就不会生效。因此，account.ProcessResponse
		//必须在util.ResponseSuccess之前调用
		account.ProcessResponse(ctx)
		until.ResponseSuccess(ctx, nil)
	}()
	err = ctx.BindJSON(&userInfo)

	if err != nil {
		//参数错误
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}

	//数据验证
	if len(userInfo.UserName) == 0 || len(userInfo.Password) == 0 {
		fmt.Println("数据验证", userInfo)
		until.ResponseError(ctx, until.ErrJudegCodeParameter)
		return
	}
	//通过
	err = db.Login(&userInfo)
	if err != nil {
		until.ResponseError(ctx, until.ErrloginErr)
		return
	}
	////cookies  设置到cooki中
	//account.SetUserId(userInfo.UserId, ctx)
	////需要在返回数据之前设置cookie 否则无效
	//account.ProcessResponse(ctx)
	//until.ResponseSuccess(ctx, nil)
}

//注册
func RegisterHandle(ctx *gin.Context) {
	var userInfo model.UserInfo
	//直接将前端给数据 赋值到结构体
	err := ctx.ShouldBindJSON(&userInfo)
	//username := ctx.PostForm("username")
	//email := ctx.PostForm("email")
	//password := ctx.PostForm("password")
	//sex := ctx.PostForm("sex")//
	//sexInt:=int(sex)
	//fmt.Printf("%T",sex)
	//var userInfo = &model.UserInfo{
	//	UserName: username,
	//	Email:    email,
	//	Password: password,
	//	//Sex:sex,
	//}

	if err != nil {
		//参数错误
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}
	//数据验证
	if len(userInfo.UserName) == 0 || len(userInfo.Email) == 0 || len(userInfo.Password) == 0 {
		fmt.Println("数据验证registers", userInfo)
		until.ResponseError(ctx, until.ErrJudegCodeParameter)
		return
	}
	//userInfo.UserId, err = id_gen.GetId()
	userId, err := id_gen.GetId()
	userInfo.UserId = int64(userId)
	//通过
	err = db.Register(&userInfo)
	if err == db.ErrUserExists {
		until.ResponseError(ctx, until.ErrCodeExist)
		return
	}
	if err != nil { //服务端失败
		until.ResponseError(ctx, until.ErrCodeServerErr)
		return
	}
	//返回消息提示 成功
	until.ResponseSuccess(ctx, nil)
}
